package com.stone.im.geteway.tcp;

import com.stone.im.geteway.push.PushManager;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class GatewayTcpServer {

    public static final int PORT = 8002;

    public static void main(String[] args) {
        System.out.println("tcp接入系统开始启动...");
        new PushManager().start();
        NioEventLoopGroup connectionThreadGroup = new NioEventLoopGroup();
        NioEventLoopGroup ioThreadGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap server = new ServerBootstrap();

            server.group(connectionThreadGroup,ioThreadGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>(){
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ByteBuf delimiter = Unpooled.copiedBuffer("&_".getBytes());
                            socketChannel.pipeline().addLast(new GatewayTcpHandler());
                            socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(4096,delimiter));
                        }
                    });


            ChannelFuture channelFuture = server.bind(PORT).sync();

            System.out.println("tcp接入系统已经启动...");
            channelFuture.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            connectionThreadGroup.shutdownGracefully();
            ioThreadGroup.shutdownGracefully();
        }
    }
}
